<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Category;

class Goods extends Common
{
    public function index(){
        //获取分类树
        $categoryArray = Db::name('category')->order('sort')->select();
        $categoryList = Category::tree($categoryArray);

        //获取一级分类ID
       $id = input('id',0); //二级分类ID
        $pid = Db::name('category')->where('id',$id)->value('pid');

        $this->assign(['categoryList'=>$categoryList, 'pid'=>$pid ? $pid : $categoryList[0]['id']]);

        return view();
    }

    public function content($id = 0){
        if($id){
            $infoList = Db::name('goods')->where('cid_two',$id)->order('id desc')->select();
            //获取分类名称
            $catname = getCatInfoById($id,'name');
            $this->assign(['name'=>$catname,'infoList'=>$infoList]);
        }
        return view();
    }

    public function add($id = 0){
        if(request()->isPost()){
            $data = input('post.');

            // 判断商品规格
            $spec_type = $data['spec_type'];
            if($spec_type == '2'){
                $item = input('post.item/a');
                if(count($item) == 0){
                    return error('请添加相应规格项或选择单规格发布');
                }
            }

            //获取上级分类ID
            $data['cid_one'] = Db::name('category')->where('id',$data['cid_two'])->value('pid');
            $goods_id = Db::name('goods')->strict(false)->insertGetId($data);
            if($goods_id){
                if($spec_type == '2'){
                    //修改商品表价格、库存和重量
                    foreach ($item as $key => $value) {
                        // 批量添加数据
                        $value['price'] = trim($value['price']);
                        $value['store'] = trim($value['store']);
                        $value['weight'] = trim($value['weight']);
                        $datalist[] = [
                            'gid' => $goods_id,
                            'key' => $key,
                            'key_value' => $value['key_value'],
                            'price' => $value['price'],
                            'store' => $value['store'],
                            'weight' => $value['weight']
                        ];
                    }
                    Db::name('goods_spec')->insertAll($datalist);
                    //更新当前商品的价格等信息
                    Db::name('goods')->where('id', $goods_id)->update(['price'=>$datalist[0]['price'], 'store'=>$datalist[0]['store'], 'weight'=>$datalist[0]['weight']]);
                }
                return success('商品添加成功',url('index',['id'=>$data['cid_two']]));
            }else{
                return error('商品添加失败');
            }
        }else{
            //获取分类名称
            $catname = getCatInfoById($id,'name');
            $this->assign('name',$catname);
            return view();
        }
    }

    //商品编辑
    public function edit($id = 0){
        if(request()->isPost()){
            $data = input('post.');

            // 第三季升级
            // 判断商品规格
            $spec_type = $data['spec_type'];
            if($spec_type == '2'){
                $item = input('post.item/a');
                if(count($item) == 0){
                    return error('请添加相应规格项或选择单规格提交编辑');
                }
            }

            $result = Db::name('goods')->strict(false)->update($data);

            // 第三季升级
            Db::name('goods_spec')->where('gid', $data['id'])->delete();

            if($result !== false){
                if($spec_type == '2'){
                    //修改商品表价格、库存和重量
                    foreach ($item as $key => $value) {
                        // 批量添加数据
                        $value['price'] = trim($value['price']);
                        $value['store'] = trim($value['store']);
                        $value['weight'] = trim($value['weight']);
                        $datalist[] = [
                            'gid' => $data['id'],
                            'key' => $key,
                            'key_value' => $value['key_value'],
                            'price' => $value['price'],
                            'store' => $value['store'],
                            'weight' => $value['weight']
                        ];
                    }
                    Db::name('goods_spec')->insertAll($datalist);
                    //更新当前商品的价格等信息
                    Db::name('goods')->where('id', $data['id'])->update(['price'=>$datalist[0]['price'], 'store'=>$datalist[0]['store'], 'weight'=>$datalist[0]['weight']]);
                }
                return success('商品信息编辑成功',url('index',['id'=>$data['cid_two']]));
            }else{
                return error('商品信息编辑失败');
            }
        }else{
            //获取商品信息
            $goods = Db::name('goods')->where('id',$id)->find();
            //分类名称
            $catname = getCatInfoById($goods['cid_two'], 'name');
            $this->assign(['info'=>$goods, 'id'=>$goods['cid_two'], 'name'=>$catname]);//id为二级分类
            return view();
        }
    }

    public function delete($id = 0, $cid_two = 0){
        if(Db::name('goods')->where('id',$id)->delete()){
            return success('删除成功',url('content',['id'=>$cid_two]));
        }else{
            return error('删除失败');
        }
    }

    public function deleteAll(){
        $cid = input('post.cid');
        $ids = input('post.ids/a');
        if(empty($ids)){
            return error('请选中需要删除的数据');
        }
        foreach (input('post.ids/a') as $key => $value) {
            Db::name('goods')->where('id',$key)->delete();
        }
        return success('批量删除成功',url('content',['id'=>$cid]));
    }

    public function addImg($id = 0, $cid_two = 0){
        if(request()->isPost()){
            // 将图片字符串转数组遍历添加
            $post = input('post.');
            $imagesStr = $post['imagesStr'];
            $images = explode(',',$imagesStr); //字符串转数组
            $data['gid'] = $post['id']; //商品ID
            //删除原数据
            Db::name('goods_images')->where('gid',$post['id'])->delete();
            if(trim($imagesStr)!=''){
                foreach ($images as $key => $value) {
                    $data['img'] = $value;
                    Db::name('goods_images')->insert($data);
                }
            }
            return success('图片添加成功',url('index',['id'=>$cid_two]));
        }else{
            // 获取当前商品所有图片
            $goodsImages = Db::name('goods_images')->where('gid',$id)->select();
            $images = Db::name('goods_images')->where('gid',$id)->column('img');
            $imagesStr = implode(',',$images); //数组转字符串
            $this->assign(['goodsImages'=>$goodsImages, 'imagesStr'=>$imagesStr]);
            return view();
        }
    }

    //删除图片或文件
    public function delete_file(){
        $delete_url = input('img');
        try {
            unlink(ROOT_PATH . 'public/uploads/' . $delete_url); //删除成功返回1
        } catch (Exception $e) {

        }
    }

    public function getDataTables($id = 0) {
        if($id){
            //获取请求过来的数据
            $getParam = request()->param();

            $draw = $getParam['draw'];

            //排序
            $orderSql = $getParam['order'][0]['dir'];

            //自定义查询参数
            $extra_search = $getParam['extra_search'];

            // 总记录数
            $recordsTotal = Db::name('goods')->where('cid_two',$id)->count();
            //过滤条件后的总记录数
            $search = $getParam['search']['value'];
            $recordsFiltered = strlen($search) ?  Db::name('goods')->where('cid_two',$id)->where($extra_search,'like','%'.$search.'%')->count() : $recordsTotal;

            //分页
            $start = $getParam['start']; //起始下标
            $length = $getParam['length']; //每页显示记录数

            //根据开始下标计算出当前页
            $page = intval($start/$length) + 1;
            $config = ['page'=>$page, 'list_rows'=>$length];
            $list = Db::name('goods')->where('cid_two',$id)->where($extra_search,'like','%'.$search.'%')->order($orderSql)->paginate(null,false,$config);
            $lists = [];
            $uploads_tem = config('view_replace_str.__UPLOADS__').'/';
            if(!empty($list)){
                foreach ($list as $key => $value) {
                    $lists[$key] = $value;
                    $lists[$key]['img'] = $value['img'] ? "<img src='".$uploads_tem.$value['img']."' alt='".$value['name']."' width='36'>" : '';
                    $lists[$key]['operate'] = "<a href='". url('edit',['id'=>$value['id']]) ."' title='编辑' target='_parent'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                    <a href='". url('addImg',['id'=>$value['id'], 'cid_two'=>$value['cid_two']]) ."' title='添加图片' target='_parent'><i class='fa fa-picture-o text-navy'></i></a>&nbsp;&nbsp;
                    <a id='".$value['id']."' href='javascript:;' class='evaluate' title='评价管理'><i class='fa fa-commenting-o text-navy'></i></a>&nbsp;&nbsp;
                    <a name='delete' href='". url('delete',['id'=>$value['id'], 'cid_two'=>$value['cid_two']]) ."' title='删除'><i class='fa fa-trash-o text-navy'></i></a>";
                }
            }
        } else{
            $draw = 1;
            $recordsTotal = 0;
            $recordsFiltered = 0;
            $lists = [];
        }

        $data = array(
            "draw"=>$draw,
            "recordsTotal"=>$recordsTotal, //数据总数
            "recordsFiltered"=>$recordsFiltered, //过滤之后的记录总数
            "data"=>$lists
        );

        echo json_encode($data);
    }

    // 商品评价
    public function evaluate($id = 0){
        return view();
    }

    public function getDataTablesEvaluate() {
        //获取请求过来的数据
        $getParam = request()->param();

        $draw = $getParam['draw'];

        //排序
        $orderSql = $getParam['order'][0]['dir'];

        //自定义查询参数
        $extra_search = $getParam['extra_search'];

        //获取表名
        $tablename = 'comment';

        // 商品ID
        $gid = input('id', 0);

        // 总记录数
        $recordsTotal = Db::name($tablename)->count();
        //过滤条件后的总记录数
        $search = $getParam['search']['value'];
        $recordsFiltered = strlen($search) ?  Db::name($tablename)->where('gid', $gid)->count() : $recordsTotal;

        //分页
        $start = $getParam['start']; //起始下标
        $length = $getParam['length']; //每页显示记录数

        //根据开始下标计算出当前页
        $page = intval($start/$length) + 1;
        $config = ['page'=>$page, 'list_rows'=>$length];
        $list = Db::name($tablename)->where('gid', $gid)->order($orderSql)->paginate(null,false,$config);
        $lists = [];
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $lists[$key] = $value;
                $userInfo = Db::name('user')->where('id', $value['uid'])->field('nickname,head')->find();
                $lists[$key]['nickname'] = $userInfo['nickname'];
                $lists[$key]['head'] = "<img src='".$userInfo['head']."' width=36>";
            }
        }

        $data = array(
            "draw"=>$draw,
            "recordsTotal"=>$recordsTotal, //数据总数
            "recordsFiltered"=>$recordsFiltered, //过滤之后的记录总数
            "data"=>$lists
        );

        echo json_encode($data);
    }

    //获取商品规格
    public function getSpecAttr($cid = 0, $gid = 0){
        $specList = Db::name('spec')->where('cid', $cid)->order('sort')->select();
        // gid为真时为编辑功能
        if($gid){
            // 编辑商品信息时调用规格
            $goods_spec = Db::name('goods_spec')->where('gid', $gid)->order('id')->column('id,key');
            $keys_array = array();
            foreach ($goods_spec as $key => $value) {
                $keys_array = array_merge($keys_array, explode('_',$value)); //组合数组 ["7","18","8","18"]
            }
            $keys_array = array_unique($keys_array); //去除重复数组元素["7","18","8"]
            $keys = implode(',', $keys_array);
            foreach ($specList as $key => $value) {
                $specList[$key]['item'] = Db::name('spec_item')->where('spec_id', $value['id'])->where('id','IN',$keys)->order('id')->select();
            }
        }
        $this->assign('gid',$gid);
        $this->assign('specList',$specList);
        return view('spec');
    }

    public function addSpecItem(){
        // 规格id
        $spec_id = input('spec_id', 0);
        // 规格项
        $spec_item = input('spec_item', '');
        $count = Db::name('spec_item')->where('spec_id', $spec_id)->where('item', $spec_item)->count();
        //规格项存在则返回其ID
        if($count){
            $id = Db::name('spec_item')->where('spec_id', $spec_id)->where('item', $spec_item)->value('id'); //原ID
        }else {
            $id = Db::name('spec_item')->insertGetId(['spec_id'=>$spec_id, 'item'=>$spec_item]); //新ID
        }
        return success($id);
    }

    public function getSpecItem($gid = 0){
        // {"1":[7,8],"2":[9]}
        $spec_arr = input('post.spec_arr/a'); //获取数组需加/a
        if(count($spec_arr) == 0)
            exit('');
        // consoleLog($spec_arr);
        // 获取规格的笛卡尔积
        foreach ($spec_arr as $k => $v) {
            $spec_arr_sort[$k] = count($v);
        }
        //对数组元素从低到高进行排序并保持索引关系
        asort($spec_arr_sort);
        // consoleLog($spec_arr_sort); //{"2":1,"1":2}
        foreach ($spec_arr_sort as $key => $value) {
            $spec_array[$key] = $spec_arr[$key];
        }
        // consoleLog($spec_array); //{"3":["20"],"2":["18","19"],"1":["7","8","17"]}
        // 返回数组中所有键名组成一个新数组
        $clo_name = array_keys($spec_array);
        // consoleLog($clo_name); //[3,2,1]
        $spec_array = combineDika($spec_array);
        //[["20","18","7"],["20","18","8"],["20","18","17"],["20","19","7"],["20","19","8"],["20","19","17"]]
        // consoleLog($spec_array);

        // 规格表
        $spec = Db::name('spec')->column('id,name');
        $clo_name_str = implode(',',$clo_name);
        // 规格项表
        $specItem_arr = Db::name('spec_item')->where('spec_id','IN',$clo_name_str)->select();

        // 编辑功能
        if($gid){
            $goods_spec = Db::name('goods_spec')->where('gid', $gid)->column('key,key_value,price,store,weight');//规格项
        }

        $str = "<table id='spec_input_table' class='table table-bordered'>";
        $str .= "<tr>";
        // 表格第一行
        foreach ($clo_name as $key => $value) {
            $str .= "<td><b>{$spec[$value]}</b></td>";
        }
        $str .= "<td><b>价格</b></td>
                <td><b>库存</b></td>
                <td><b>重量(kg)</b></td>
                </tr>";

        $specItem = array();
        foreach ($specItem_arr as $key => $value) {
            $specItem[$value['id']]['item'] = $value['item'];
            $specItem[$value['id']]['spec_id'] = $value['spec_id'];
        }

        // $spec_array = [["20","18","7"],["20","18","8"],["20","18","17"],["20","19","7"],["20","19","8"],["20","19","17"]];
        foreach ($spec_array as $k => $v) {
            $str .= "<tr>";
            $item_key_name = array();
            foreach ($v as $k2 => $v2) {
                $str .= "<td>{$specItem[$v2]['item']}</td>";
                // 规格一:规格1-1
                $item_key_name[$v2] = $spec[$specItem[$v2][spec_id]] . ':' . $specItem[$v2]['item'];
            }
            // 按照键名对关联数组进行升序排序
            ksort($item_key_name);
            // consoleLog($item_key_name); //{"7":"规格一:111","18":"规格二:444","20":"规格三:666"}
            // array_keys返回数组中所有键名的一个新数组
            $item_key = implode('_', array_keys($item_key_name)); // 7_18_20
            $item_name = implode(' ', $item_key_name); //规格一:111 规格二:444 规格三:666
            $str .= "<td><input name='item[$item_key][price]' value='{$goods_spec[$item_key][price]}' /></td>";
            $str .= "<td><input name='item[$item_key][store]' value='{$goods_spec[$item_key][store]}' /></td>";
            $str .= "<td><input name='item[$item_key][weight]' value='{$goods_spec[$item_key][weight]}' />
                    <input type='hidden' name='item[$item_key][key_value]' value='$item_name'</td>";
            $str .= "</tr>";
        }

        $str .= "</table>";
        exit($str);
    }
}
